package com.atguigu.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.IPUtil;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author hachimen
 * @since 2021-09-03
 */
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo userDB = userInfoService.queryUserFromDB(userInfo);
        if(userDB != null){
            //存在账号密码
            Map<String, Object> retMap = new HashMap<>();
            String token = UUID.randomUUID().toString();
            retMap.put("token",token);
            retMap.put("nickName",userDB.getNickName());

            String key = RedisConst.USER_LOGIN_KEY_PREFIX+token;
            JSONObject userInfoJS = new JSONObject();
            userInfoJS.put("userId",userDB.getId().toString());
            userInfoJS.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(key,userInfoJS.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retMap);
        }else{
            //不存在
            return RetVal.fail().message("账号或密码错误");
        }

    }

    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token))
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
        return RetVal.ok();
    }


}

